package cn.jietuo.bio;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2021/2/26
 * @description: socket服务端
 */
public class SocketServer {

    public static void main(String[] args) throws IOException {
        // 开启一个服务器连接
        ServerSocket serverSocket = new ServerSocket(9000);
        while(true){
            System.out.println("等待客户端的连接。。");
            // 接受客户端请求，如果没有连接进来，这里会阻塞
            Socket clientSocket = serverSocket.accept();
            System.out.println("有客户端连接进来了。。");
            handler(clientSocket);
        }
    }

    private static void handler(Socket clientSocket) throws IOException {
        byte[] bytes = new byte[1024];
        System.out.println("准备read...");
        int read = clientSocket.getInputStream().read(bytes);
        if (read != -1){
            System.out.println("收到客户端的数据："+ new String(bytes,0,read));
        }
        clientSocket.getOutputStream().write("HelloClient".getBytes());
        clientSocket.getOutputStream().flush();
    }
}

